﻿using ContactSMS.Commons.Util;
using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.Infrastructure.dbContexts;
using ContactSMS.Infrastructure.Migrations;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Security.Claims;

namespace ContactSMS.Infrastructure
{
    public class UserRepository : IUserRepository
    {
        private readonly ContactDbContexts _contactDbContexts;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public UserRepository(ContactDbContexts contactDbContexts, IHttpContextAccessor httpContextAccessor)
        {
            this._contactDbContexts = contactDbContexts;
            this._httpContextAccessor = httpContextAccessor;
        }

        public async Task<User?> GetUserByTokenAsync()
        {
            if (_httpContextAccessor.HttpContext is not null)
            {
                var idClaim = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                var nameClaim = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);

                if (idClaim != null)
                {
                    var id = idClaim.Value;
                    var name = nameClaim?.Value ?? string.Empty;
                    // 假设存在一个通过 ID 获取用户的方法
                    var user = await this.GetUserByIdAsync(id);
                    if (user is not null)
                    {
                        // 如果需要的话，可以更新用户的名字
                        if (!string.IsNullOrEmpty(name))
                        {
                            user.UserName = name;
                        }
                        return user;
                    }
                }
            }
            // 如果没有找到有效的用户信息，则返回 null
            return null;
        }

        public async Task<User?> GetUserByIdAsync(string id)
        {
            long userId;
            if (!long.TryParse(id, out userId))
            {
                // 如果转换失败，可以选择返回 null 或抛出异常
                return null; // 或者 throw new ArgumentException("Invalid user ID.");
            }
            var result = await _contactDbContexts.Users.Where(o => o.Id == userId).FirstOrDefaultAsync();
            return result;
        }

        public async Task<User?> GetUserByUserNameAsync(string username)
        {
            var result = await _contactDbContexts.Users.Where(o => o.UserName == username).FirstOrDefaultAsync();
            return result;
        }

        public async Task<bool> ChangePassWordAsync(string PassWord)
        {
            var user = await this.GetUserByTokenAsync();
            if (user != null)
            {
                user.PassWord = PassWordUtil.HashPassword(PassWord);
                user.UpdateTime = TimeUtil.GetTimestamp();
                await _contactDbContexts.SaveChangesAsync();
                return true;
            }
            return false;
        }
    }
}
